package com.cloud.message.rocketmq;

import com.cloud.common.sentinel.Sentinel;
import com.cloud.common.util.JsonUtils;
import com.cloud.message.entity.MessagePending;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Sentinel
@Component
public class RocketMQSender {

    public static final String TOPIC_PREFIX = "Message";

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public boolean sendMessage(MQMessage message) {
        SendResult sendResult = rocketMQTemplate.syncSendOrderly(TOPIC_PREFIX + message.getLevel(), JsonUtils.toJSONString(message), message.getHashKey());
        if (sendResult.getSendStatus() == SendStatus.SEND_OK) {
            return true;
        }
        log.error("send message failure, status={} message={}", sendResult.getSendStatus(), message);
        return false;
    }

    public boolean sendPending(MessagePending pending) {
        SendResult sendResult = rocketMQTemplate.syncSendOrderly(TOPIC_PREFIX + "Pending", JsonUtils.toJSONString(pending), pending.getHashKey());
        if (sendResult.getSendStatus() == SendStatus.SEND_OK) {
            return true;
        }
        log.error("send pending failure, status={} pending={}", sendResult.getSendStatus(), pending);
        return false;
    }

}
